import 'dart:async';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:fate_blind_box/widget/icon_text.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import '../../../network/Api.dart';
import '../../../network/http_config.dart';
import '../../../widget/date_picker/flutter_datetime_picker.dart';
import '../WebView.dart';

class ProfileCompleteV3Ui extends StatelessWidget {
  const ProfileCompleteV3Ui({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const _ProfileCompleteWidget();
  }
}

class _ProfileCompleteWidget extends StatefulWidget {
  const _ProfileCompleteWidget({Key? key}) : super(key: key);

  @override
  State<_ProfileCompleteWidget> createState() => _ProfileCompleteWidgetState();
}

class _ProfileCompleteWidgetState extends State<_ProfileCompleteWidget> {
  late Size _screen;
  final _phoneController = TextEditingController();
  final _codeController = TextEditingController();
  final _birthdayController = TextEditingController();
  final _passController = TextEditingController();
  final _surePassController = TextEditingController();
  bool _isPolicy = false;
  int _gender = 2;

  @override
  Widget build(BuildContext context) {
    _screen = MediaQuery.of(context).size;
    return SingleChildScrollView(
      child: Container(
        decoration: ShapeDecoration(
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
            color: Colors.white),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // Align(
            //   alignment: Alignment.topRight,
            //   child: IconButton(
            //     icon: const Icon(Icons.close, size: 24, color: Color(0xFFB3B3B3),),
            //     onPressed: () {
            //       Navigator.pop(context);
            //     },
            //   ),
            // ),
            const SizedBox(height: 20),
            Align(
              alignment: Alignment.topCenter,
              child: Text(
                "资料填写",
                style: TextStyle(fontSize: 18, color: ThemeColor.textColor),
              ),
            ),
            const SizedBox(
              height: 24,
            ),
            const Divider(
              color: Color(0xFFD8D8D8),
              height: 1,
            ),
            const SizedBox(
              height: 12,
            ),
            Container(
              margin: const EdgeInsets.only(left: 14),
              alignment: Alignment.topLeft,
              child: const Text(
                "性别",
                style: TextStyle(fontSize: 14),
              ),
            ),
            const SizedBox(
              height: 8,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const SizedBox(
                  width: 14,
                ),
                Expanded(
                  flex: 1,
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        _gender = 2;
                      });
                    },
                    child: Container(
                      alignment: Alignment.center,
                      height: 48,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          border: _gender == 2
                              ? Border.all(
                                  color: const Color(0xFFFF5998),
                                  width: 2,
                                )
                              : null,
                          color: Color(_gender == 2 ? 0xFFF5D8E3 : 0xFFC8CACB)),
                      child: IconText(
                        "    女士",
                        icon: Image.asset(
                          "images/ic_avatar_def_girl.png",
                          width: 32,
                          height: 32,
                        ),
                      ),
                    ),
                  ),
                ),
                const SizedBox(
                  width: 14,
                ),
                Expanded(
                  flex: 1,
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        _gender = 1;
                      });
                    },
                    child: Container(
                      alignment: Alignment.center,
                      width: (_screen.width - 42) / 2,
                      height: 48,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          border: _gender == 1
                              ? Border.all(
                                  color: const Color(0xFF59B8FF),
                                  width: 2,
                                )
                              : null,
                          color: Color(_gender == 1 ? 0xFFD8EAF5 : 0xFFC8CACB)),
                      child: IconText(
                        "    男士",
                        icon: Image.asset(
                          "images/ic_avatar_def_boy.png",
                          width: 32,
                          height: 32,
                        ),
                      ),
                    ),
                  ),
                ),
                const SizedBox(
                  width: 14,
                ),
              ],
            ),
            const SizedBox(
              height: 14,
            ),
            Container(
              alignment: Alignment.topLeft,
              margin: const EdgeInsets.only(left: 14),
              child: Text(
                "生日",
                style: TextStyle(fontSize: 14, color: ThemeColor.textColor),
              ),
            ),
            TextField(
              controller: _birthdayController,
              maxLines: 1,
              decoration: InputDecoration(
                  hintText: "请选择",
                  hintStyle: TextStyle(
                      fontSize: 14, color: ThemeColor.textColorSecond),
                  suffixIcon: Icon(
                    Icons.keyboard_arrow_right_rounded,
                    size: 24,
                    color: ThemeColor.textColorSecond,
                  ),
                  border: const OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.transparent)),
                  enabledBorder: const OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.transparent)),
                  disabledBorder: const OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.transparent)),
                  focusedBorder: const OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.transparent)),
                  contentPadding:
                      const EdgeInsets.symmetric(horizontal: 14, vertical: 0)),
              readOnly: true,
              onTap: () async {
                DatePicker.showDatePicker(context,
                    showTitleActions: true,
                    minTime: DateTime(1950, 1, 1),
                    maxTime: DateTime(2005, 12, 31),
                    onChanged: (date) {}, onConfirm: (date) {
                  // '$date'
                  _birthdayController.text = date.toString().split(' ')[0];
                }, currentTime: DateTime.now(), locale: LocaleType.zh);
                // final res = await showDatePicker(
                //     context: context,
                //     initialDate: DateTime(1980),
                //     firstDate: DateTime(1960),
                //     lastDate: DateTime.now()
                // );
                // if (res != null && res.toString().isNotEmpty) {
                //   _birthdayController.text = res.toString().split(" ")[0];
                // }
              },
            ),
            const Divider(
              color: Color(0xFFD8D8D8),
              height: 1,
            ),
            Container(
              height: 48,
              padding: const EdgeInsets.symmetric(horizontal: 12),
              margin: const EdgeInsets.symmetric(vertical: 12, horizontal: 14),
              decoration: ShapeDecoration(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(5)),
                  color: const Color(0xFFF3F4F5)),
              alignment: Alignment.centerLeft,
              child: TextField(
                controller: _phoneController,
                keyboardType: TextInputType.phone,
                maxLength: 11,
                maxLines: 1,
                decoration: const InputDecoration(
                    hintText: "请输入手机号",
                    border: InputBorder.none,
                    counterText: ''),
              ),
            ),
            Container(
                height: 48,
                padding: const EdgeInsets.symmetric(horizontal: 12),
                margin:
                    const EdgeInsets.symmetric(vertical: 12, horizontal: 14),
                decoration: ShapeDecoration(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(5)),
                    color: const Color(0xFFF3F4F5)),
                alignment: Alignment.centerLeft,
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: _codeController,
                        keyboardType: TextInputType.phone,
                        maxLength: 11,
                        maxLines: 1,
                        decoration: const InputDecoration(
                            hintText: "请输入验证码",
                            border: InputBorder.none,
                            counterText: ''),
                      ),
                    ),
                    Container(
                        width: 88,
                        height: 32,
                        decoration: BoxDecoration(
                            border: Border.all(color: const Color(0xFF2C7FF8)),
                            borderRadius: BorderRadius.circular(5),
                            color: Colors.white),
                        alignment: Alignment.center,
                        child: GestureDetector(
                          onTap: () {
                            _sendVerifyCode();
                          },
                          child: Text(
                            _curTime > 0 ? "$_curTime秒后重新获取" : "获取验证码",
                            style: const TextStyle(
                                color: Color(0xFF2C7FF8), fontSize: 12),
                          ),
                        ))
                  ],
                )),
            Container(
              height: 48,
              padding: const EdgeInsets.symmetric(horizontal: 12),
              margin: const EdgeInsets.symmetric(vertical: 12, horizontal: 14),
              decoration: ShapeDecoration(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(5)),
                  color: const Color(0xFFF3F4F5)),
              alignment: Alignment.centerLeft,
              child: TextField(
                controller: _passController,
                keyboardType: TextInputType.phone,
                maxLength: 11,
                maxLines: 1,
                decoration: const InputDecoration(
                    hintText: "请输入密码",
                    border: InputBorder.none,
                    counterText: ''),
              ),
            ),
            Container(
              height: 48,
              padding: const EdgeInsets.symmetric(horizontal: 12),
              margin: const EdgeInsets.symmetric(vertical: 12, horizontal: 14),
              decoration: ShapeDecoration(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(5)),
                  color: const Color(0xFFF3F4F5)),
              alignment: Alignment.centerLeft,
              child: TextField(
                controller: _surePassController,
                keyboardType: TextInputType.phone,
                maxLength: 11,
                maxLines: 1,
                decoration: const InputDecoration(
                    hintText: "请再次输入密码",
                    border: InputBorder.none,
                    counterText: ''),
              ),
            ),
            Container(
              margin: const EdgeInsets.only(left: 14, right: 14, bottom: 20),
              child: CheckboxListTile(
                controlAffinity: ListTileControlAffinity.leading,
                title: Text.rich(TextSpan(children: [
                  const TextSpan(
                      text: "我已仔细阅读并了解",
                      style: TextStyle(color: Color(0xFF222222), fontSize: 12)),
                  TextSpan(
                    text: "《隐私协议》",
                    style:
                        const TextStyle(color: Color(0xFF2C7FF8), fontSize: 12),
                    recognizer: TapGestureRecognizer()
                      ..onTap = () {
                        Navigator.push(context,
                            MaterialPageRoute(builder: (BuildContext context) {
                          return const Browser(
                              '隐私协议', '${HttpConfig.baseUrl}priva');
                        }));
                      },
                  ),
                  const TextSpan(
                      text: "和",
                      style: TextStyle(color: Color(0xFF222222), fontSize: 12)),
                  TextSpan(
                    text: "《服务协议》",
                    style:
                        const TextStyle(color: Color(0xFF2C7FF8), fontSize: 12),
                    recognizer: TapGestureRecognizer()
                      ..onTap = () {
                        Navigator.push(context,
                            MaterialPageRoute(builder: (BuildContext context) {
                          return const Browser(
                              '服务协议', '${HttpConfig.baseUrl}serv');
                        }));
                      },
                  )
                ])),
                value: _isPolicy,
                onChanged: (bool? value) {
                  setState(() {
                    _isPolicy = value ?? false;
                  });
                },
              ),
            ),
            GestureDetector(
              onTap: () {
                _submit();
              },
              child: Container(
                height: 48,
                margin: const EdgeInsets.symmetric(horizontal: 14),
                decoration: BoxDecoration(
                    gradient: const LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [Color(0xFFB1A3E4), Color(0xFF7278E5)]),
                    borderRadius: BorderRadius.circular(24)),
                alignment: Alignment.center,
                child: const Text(
                  "确认",
                  style: TextStyle(color: Colors.white, fontSize: 18),
                ),
              ),
            ),
            const SizedBox(
              height: 20,
            )
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  Timer? _timer;
  int _curTime = 0;

  _startCountdownTimer() {
    _curTime = 60;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        _curTime--;
      });
      if (_curTime <= 0) {
        _timer?.cancel();
      }
    });
  }

  bool _verify(bool sendCode) {
    if (_birthdayController.text.isEmpty) {
      toast("请选择生日");
      return false;
    }
    if (_phoneController.text.isEmpty) {
      toast("请输入手机号");
      return false;
    }
    if (sendCode) {
      return true;
    }
    if (_codeController.text.isEmpty) {
      toast("请输入验证码");
      return false;
    }
    if (_passController.text.isEmpty) {
      toast("请输入密码");
      return false;
    }
    if (_surePassController.text.isEmpty) {
      toast("请再次输入密码");
      return false;
    }
    if (!_isPolicy) {
      // toast("请仔细阅读并了解《隐私协议》和《服务协议》");
      _versionOfdown(context, "请仔细阅读并了解《隐私协议》和《服务协议》");
      return false;
    }
    return true;
  }

  Future<void> _versionOfdown(context, String title) async {
    showCupertinoDialog(
        context: context,
        builder: (context) {
          return CupertinoAlertDialog(
            title: Text.rich(TextSpan(children: [
              const TextSpan(
                  text: "请仔细阅读并同意",
                  style: TextStyle(color: Color(0xFF222222), fontSize: 12)),
              TextSpan(
                text: "《隐私协议》",
                style: TextStyle(color: ThemeColor.appColor, fontSize: 12),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    Navigator.push(context,
                        MaterialPageRoute(builder: (BuildContext context) {
                      return const Browser(
                          '隐私协议', '${HttpConfig.baseUrl}priva');
                    }));
                  },
              ),
              const TextSpan(
                  text: "和",
                  style: TextStyle(color: Color(0xFF222222), fontSize: 12)),
              TextSpan(
                text: "《服务协议》",
                style: TextStyle(color: ThemeColor.appColor, fontSize: 12),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    Navigator.push(context,
                        MaterialPageRoute(builder: (BuildContext context) {
                      return const Browser('服务协议', '${HttpConfig.baseUrl}serv');
                    }));
                  },
              )
            ])),
            actions: <Widget>[
              CupertinoDialogAction(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: const Text(
                  '不同意',
                  style: TextStyle(fontSize: 16, color: Colors.black),
                ),
              ),
              CupertinoDialogAction(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text(
                  '同意并继续',
                  style: TextStyle(fontSize: 16, color: ThemeColor.appColor),
                ),
              ),
            ],
          );
        });
  }

  String? _smsSig;

  _sendVerifyCode() {
    if (!_verify(true)) {
      return;
    }
    loading(() async {
      final res = await Api.getInstance().loginSendCode(_phoneController.text);
      if (res['code'] == 0) {
        if (res['data'] != null && res['data']['sig'] != null) {
          _smsSig = res['data']['sig'];
          _startCountdownTimer();
        } else {
          toast("验证码发送失败");
        }
      } else {
        toast(res['msg']);
      }
    });
  }

  _submit() {
    if (!_verify(false)) {
      return;
    }
    if (_smsSig == null || _smsSig!.isEmpty) {
      toast("请先获取验证码");
      return;
    }
    loading(() async {
      final res = await Api.getInstance().completeInfoByWxLogin(
        _phoneController.text,
        _codeController.text,
        _smsSig!,
        _gender,
        _birthdayController.text,
        _passController.text,
        _surePassController.text,
      );
      if (res['code'] == 0) {
        Navigator.pop(context);
      } else {
        toast(res['msg']);
      }
    });
  }
}
